/* 双向绑定 */
var aUser, uUser;
var uc = new UserComponent();
window.onload = function(){
	//初始化
	uc.queryAllUser();
	initAddUser(uc);
}

function initAddUser(uc){
	$("#add-user-template").parent().children("[id!=add-user-template]").remove();
	
	var randomId = new Date().getTime();
	$("#add-user-template").parent().attr("id", randomId);
	aUser = v.render(randomId, {id:"",name:"",sex:"",salary:"",birth:""}, "add-user-template", randomId,function(){
		//绑定Add事件
		$(".btn-add").click(function(){
			uc.addUser(aUser.data);
		});
	});
}

function UserComponent(){
	this.models = [];
	
	this.addUser = function(user){
		ajaxUtil.ajax("post","/webmvcDemo/user/add", user, null, this, function(obj){
			if(obj.code==200){
				this.models.push(obj.data);
				//清空
				initAddUser();
				_render(this.models, "listTemplate", "list-body");
			}
		});
	};
	this.updateUser = function(user){
		ajaxUtil.ajax("post","/webmvcDemo/user/update", user, null, this, function(obj){
//			if(obj.code==200){
//				this.models.push(obj.data);
//				//清空
//				for(var prop in aUser.data){
//					aUser.data[prop] = "";
//				}
//				_render(this.models, "listTemplate", "list-body");
//			}
		});
	};
	this.queryAllUser = function(){
		ajaxUtil.ajax("get","/webmvcDemo/user/listAll", null, null, this, function(obj){
			if(obj.code==200){
				this.models = obj.data;
				_render(this.models,"listTemplate", "list-body");
			}
		});
	};
	
	function _render(data, templateId, targetId){
		$("#"+targetId).children("[id!="+templateId+"]").remove();
		
		data.forEach(function(item){
			v.render(item.id, item, templateId, targetId, function(){});
		});
		
		//绑定update和delete按钮事件
		$(".btn-update").click(function(){
			var id = $(this).parent().parent().attr("id");
			$("#input-id").val(id);
			var user = uc.get(id);
			uUser = v.update(user, "update-body");
			$("#updateModal").modal("show");
		});
		
		$(".btn-delete").click(function(){
			var id = $(this).parent().parent().attr("id");
			ajaxUtil.ajax("post","/webmvcDemo/user/"+id+"/delete",null,null,this,function(obj){
				if(obj.code==200){
					data=data.filter(function(item){
						return item.id!=id;
					});
					_render(data);
				}
			});
		});
	};
	
	this.get = function(id){
		for(var i = 0; i < this.models.length; i++){
			if(this.models[i].id == id){
				return this.models[i];
			}
		}
	}
	
	return this;
}
